package org.jeecg.modules.biz.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.jeecg.common.api.vo.Result;
import org.jeecg.modules.base.tappuser.entity.TAppUser;
import org.jeecg.modules.base.tappuser.mapper.TAppUserMapper;
import org.jeecg.modules.base.tnotice.mapper.TNoticeMapper;
import org.jeecg.modules.base.treadnotice.entity.TReadNotice;
import org.jeecg.modules.base.treadnotice.mapper.TReadNoticeMapper;
import org.jeecg.modules.biz.response.OwnNoticeResponse;
import org.jeecg.modules.biz.service.INoticeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class NoticeServiceImpl implements INoticeService {

    @Autowired
    private TNoticeMapper noticeMapper;

    @Autowired
    private TAppUserMapper appUserMapper;

    @Autowired
    private TReadNoticeMapper readNoticeMapper;

    @Override
    public Page<OwnNoticeResponse> ownNotice(Page<OwnNoticeResponse> page, String sysUserId) {
        TAppUser appUser = appUserMapper.selectOne(new QueryWrapper<TAppUser>().eq("link_sys_user_id", sysUserId));
        return page.setRecords(noticeMapper.selectOwnNotice(page, appUser.getId()));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<Void> readNotice(String noticeId, String sysUserId) {
        TAppUser appUser = appUserMapper.selectOne(
                new QueryWrapper<TAppUser>().eq("link_sys_user_id", sysUserId));
        List<TReadNotice> readNoticeList = readNoticeMapper.selectList(
                new QueryWrapper<TReadNotice>().eq("user_id", appUser.getId()).eq("notice_id", noticeId));
        if (CollectionUtil.isNotEmpty(readNoticeList)) {
            return Result.error("已经阅读");
        } else {
            TReadNotice readNotice = new TReadNotice();
            readNotice.setUserId(appUser.getId());
            readNotice.setNoticeId(noticeId);
            readNoticeMapper.insert(readNotice);
            return Result.ok();
        }
    }

}
